#include "UmlApplication.h"
#include "Utils.h"

#include <DLog>
#include <DWidgetUtil>
#include <DApplicationSettings>

#include <QWindow>
#include <QDesktopWidget>

DCORE_USE_NAMESPACE

class UmlApplicationPrivate
{
public:
    UmlApplicationPrivate(UmlApplication *q) : q_ptr(q) {}
    ~UmlApplicationPrivate();

    void init();

private:
    Q_DECLARE_PUBLIC(UmlApplication)
    UmlApplication *const q_ptr = Q_NULLPTR;
    DApplicationSettings *m_appSettings = Q_NULLPTR;
};

UmlApplicationPrivate::~UmlApplicationPrivate()
{
    SAFE_DELETE(m_appSettings)
}

void UmlApplicationPrivate::init()
{
    Q_Q(UmlApplication);

    q->setAttribute(Qt::AA_UseHighDpiPixmaps);
    q->setOrganizationName("deepin");
    q->setApplicationName("MagicUML");
    q->setApplicationVersion("1.0.0.0");
    q->setProductIcon(QIcon::fromTheme("uml_logo"));

    q->loadTranslator();

    q->setProductName(UmlApplication::tr("MagicUML Activation Tool"));
    q->setApplicationDescription(UmlApplication::tr("MagicUML Activation Tool."));
    q->setAutoActivateWindows(true);
}

UmlApplication *UmlApplication::m_self = Q_NULLPTR;

UmlApplication::UmlApplication(int &argc, char **argv)
    : DApplication(argc, argv)
    , d_ptr(new UmlApplicationPrivate(this))
{
    Q_D(UmlApplication);

    Q_ASSERT_X(!m_self, "UmlApplication", "there should be only one application object");
    m_self = this;

    d->init();
    registerLogger();
    setThemeAutoSaved(true);
}

UmlApplication::~UmlApplication()
{
    Q_D(UmlApplication);

    delete d;
}

UmlApplication *UmlApplication::instance()
{
    return m_self;
}

void UmlApplication::setThemeAutoSaved(bool saved)
{
    Q_D(UmlApplication);

    if (saved) {
        if (d->m_appSettings == Q_NULLPTR)
            d->m_appSettings = new DApplicationSettings();
    } else {
        SAFE_DELETE(d->m_appSettings);
    }
}

bool UmlApplication::isThemeAutoSaved() const
{
    Q_D(const UmlApplication);

    return (d->m_appSettings != Q_NULLPTR);
}

void UmlApplication::registerLogger(const QString &path)
{
    if (!path.isEmpty()) {
        QFileInfo info(path);
        QString logDir = info.absolutePath();
        QDir dir;

        if (!dir.exists(logDir)) {
            bool ok = dir.mkpath(logDir);
            if (!ok)
                qWarning() << QString("mkpath [%1] failed").arg(logDir);
        }

        DLogManager::setlogFilePath(path);
    }

    DLogManager::registerConsoleAppender();
    DLogManager::registerFileAppender();
}

QString UmlApplication::loggerPath() const
{
    return DLogManager::getlogFilePath();
}
